﻿using System;
using System.Data;
using System.Data.SqlClient;

namespace DataAccess
{
    /// <summary>
    /// This class helps make connections and access to SQL Server 
    /// </summary>
    
    public class DataAccessLayer
    {
        // To create a connection to SQL Server
        public SqlConnection CreateConnection()
        {
            // Connection string
            const string connectionString = "Data source = .; Initial Catalog = DBGroupThree; User ID = sa; Password = ";

            return new SqlConnection(connectionString); // Return a sql connection
        }

        // To get datatable on a connection created before
        public DataTable GetDataTable(string sql)
        {
            var connection = CreateConnection(); // Init a variable connection

            try
            {
                var sqlCommand = new SqlCommand(sql, connection);
                connection.Open();

                // Declare a variable SqlDataReader
                var dr = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);

                using (var dt = new DataTable())
                {
                    if (dr != null) dt.Load(dr);
                    sqlCommand.Dispose();
                    return dt;
                }
            }
            catch (SqlException)
            {
                return null;
            }
            catch (Exception)
            {
                // Notes: Here Errors may not be managed. So it is the exception level.
                return null;
            }
            finally
            {
                connection.Close();
            }
        }

        // Execute a sql command
        public string ExecuteSqlCommand(string sql)
        {
            var connection = CreateConnection(); // Init a variable connection

            try
            {
                var sqlCommand = new SqlCommand(sql, connection);
                connection.Open();
                sqlCommand.ExecuteNonQuery();
                sqlCommand.Dispose();
                return "Successfully!"; // Operation to database is ok.
            }
            catch (SqlException se)
            {
                return "So sorry, unsuccessfully! " + se.Message;
            }
            catch (Exception e)
            {
                // Notes: Here Errors may not be managed. So it is the exception level.
                return "So sorry, unsuccessfully! " + e.Message;
            }
            finally
            {
                connection.Close();
            }
        }
    }
}
